﻿using HCMS.CommonDtos;
using HCMS.Extensions;
using Microsoft.AspNetCore.Mvc;
using System.Text;

namespace HCMS.Web.Manage.Controllers.Module.Logs
{
    /// <summary>
    /// Log4Net 日志
    /// </summary>
    public class Log4NetController : ModuleController
    {
        private readonly IHostEnvironment _hostEnvironment;

        public Log4NetController(IHostEnvironment hostEnvironment)
        {
            _hostEnvironment = hostEnvironment;
        }

        #region 列表
        /// <summary>
        /// 列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult List()
        {
            return View($"{BasePath}/Logs/Log4Net/List.cshtml");
        }

        /// <summary>
        /// 列表 Ajax
        /// </summary>
        /// <remarks>
        /// 获取 Log4Net 文本日志列表
        /// </remarks>
        /// <returns></returns>
        [ActionName("List")]
        [HttpPost]
        public IActionResult PostList()
        {
            var result = new List<object>();

            // 应用基础目录
            var baseDirectory = AppContext.BaseDirectory;
            var logsDirectory = baseDirectory + "/logs";

            // 文件大小单位格式化
            Func<long, string> sizeFormat = delegate (long size)
            {
                if (size <= 0)
                {
                    return "无内容";
                }
                else if (size > 0 && size <= 1024)
                {
                    return $"{size} b";
                }
                else if (size > 1 * 1024 && size <= 1024 * 1024)
                {
                    return $"{(float)size / 1024:F2} KB";
                }
                else if (size > 1 * 1024 * 1024 && size <= 1024 * 1024 * 1024)
                {
                    return $"{(float)size / 1024 / 1024:F2} MB";
                }
                return "未知大小";
            };

            var searchArgs = new SearchArgsDto()
            {
                SearchName = Request.Form["searchName"].ToString(""),
                SearchKey = Request.Form["searchKey"].ToString("")
            };

            if (Directory.Exists(logsDirectory))
            {
                // 获取 logs 下的子级目录【error、info、debug】
                DirectoryInfo directoryInfo = new DirectoryInfo(logsDirectory);
                DirectoryInfo[] subDirectories = directoryInfo.GetDirectories();

                foreach (DirectoryInfo subDirectory in subDirectories)
                {
                    // 获取子级目录里面的文件
                    FileInfo[] files = subDirectory.GetFiles();
                    if (files == null || files.Length == 0)
                    {
                        continue;
                    }

                    // 按 创建时间 倒序排列文件
                    files = files.OrderByDescending(f => f.CreationTime).ToArray();

                    foreach (FileInfo file in files)
                    {
                        // 日志无内容，列表不显示
                        if (file.Length == 0) { continue; }

                        // 搜索指定日志文件
                        if (searchArgs.SearchName.Equals("fileName") && !string.IsNullOrWhiteSpace(searchArgs.SearchKey) &&
                            !file.Name.Contains(searchArgs.SearchKey))
                        {
                            continue;
                        }

                        result.Add(new
                        {
                            type = subDirectory.Name,
                            fileName = file.Name,
                            size = sizeFormat(file.Length)
                        });
                    }

                }
            }

            return Json(new { code = 0, data = result, count = result.Count, msg = "ok" });
        }
        #endregion

        #region 详情
        /// <summary>
        /// 详情
        /// </summary>
        /// <returns></returns>
        public IActionResult Detail(string type, string fileName)
        {
            // 应用基础目录
            var baseDirectory = AppContext.BaseDirectory;
            var logsDirectory = baseDirectory + "/logs";

            var logsFilePath = string.Empty;

            if (Directory.Exists(logsDirectory))
            {
                // 获取 logs 下的子级目录【error、info、debug】
                DirectoryInfo directoryInfo = new DirectoryInfo(logsDirectory);
                DirectoryInfo[] subDirectories = directoryInfo.GetDirectories();

                foreach (DirectoryInfo subDirectory in subDirectories)
                {
                    if (!subDirectory.Name.Equals(type)) { continue; }

                    // 获取子级目录里面的文件
                    FileInfo[] files = subDirectory.GetFiles();
                    if (files == null || files.Length == 0)
                    {
                        continue;
                    }

                    foreach (FileInfo file in files)
                    {
                        if (!file.Name.Equals(fileName)) { continue; }

                        logsFilePath = file.FullName;
                    }
                }
            }

            // 读取日志文件内容
            var result = "";
            if (!string.IsNullOrWhiteSpace(logsFilePath))
            {
                FileStream fileStream = new FileStream(logsFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                if (fileStream.Length > 0)
                {
                    byte[] buffer = new byte[fileStream.Length];
                    fileStream.Read(buffer, 0, buffer.Length);
                    fileStream.Close();
                    result = Encoding.UTF8.GetString(buffer);

                    result = result.Replace("\r\n", "<br />");
                }
            }

            ViewData["logsContent"] = result;

            return View($"{BasePath}/Logs/Log4Net/Detail.cshtml");
        }
        #endregion
    }
}
